/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY. 
 * See the GNU General Public License for more details.
 * 
 * Copyright (C) 2011 CellObject.net
 */
package net.cellobject.javacodeformatter.view;

import net.cellobject.javacodeformatter.handler.CopyFormatterHandler;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.ui.part.ResourceTransfer;

/**
 * Provide support for dragging the selected objects out of the Favorites view into another view or application.
 */
public class FormatterDragSource implements DragSourceListener {
	private final TableViewer viewer;

	public FormatterDragSource(final TableViewer viewer) {
		this.viewer = viewer;
		final DragSource source = new DragSource(viewer.getControl(), DND.DROP_COPY);
		source.setTransfer(new Transfer[]{TextTransfer.getInstance(), ResourceTransfer.getInstance()});
		source.addDragListener(this);
	}

	public void dragStart(final DragSourceEvent event) {
		event.doit = !viewer.getSelection().isEmpty();
	}

	public void dragSetData(final DragSourceEvent event) {
		final Object[] objects = ((IStructuredSelection)viewer.getSelection()).toArray();
		if (ResourceTransfer.getInstance().isSupportedType(event.dataType)) {
			event.data = CopyFormatterHandler.asResources(objects);
		} else if (TextTransfer.getInstance().isSupportedType(event.dataType)) {
			event.data = CopyFormatterHandler.asText(objects);
		}
	}

	public void dragFinished(final DragSourceEvent event) {
		// If this was a MOVE operation, 
		// then remove the items that were moved.
	}
}
